package com.bjfu.gmms.servlet.mentorServlet;

import com.bjfu.gmms.MyBatisUtil;
import com.bjfu.gmms.mapper.FreeSelectMapper;
import com.bjfu.gmms.mapper.MentorMapper;
import com.bjfu.gmms.mapper.PhaseMapper;
import com.bjfu.gmms.mapper.StudentMapper2;
import com.bjfu.gmms.model.*;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Map;

// 处理href的跳转，WEB-INF下的jsp不能直接访问，需要servlet内部转发
// Servlet 只会拦截 客户端发起的 HTTP 请求（例如 GET、POST 等）
@WebServlet("/mentor_view/*")
public class MenorPageRedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getRequestURI();

        // 根据路径进行转发
        if (path.endsWith("/mentor_info.jsp")) {
            // 导师信息修改
            request.getRequestDispatcher("/WEB-INF/mentor_view/mentor_info.jsp").forward(request, response);
        } else if (path.endsWith("/mentorSystem.jsp")) {
            // 进入志愿选择总页面
            try(SqlSession sqlSession = MyBatisUtil.getSqlSession("development")){
                PhaseMapper phaseMapper = sqlSession.getMapper(PhaseMapper.class);
                // 学科秘书 是3
                int period = phaseMapper.getPeriodByCollegeIdAndId(4, 3);
                // System.out.println(period);
                request.getSession().setAttribute("selectPhase", period);
            }
            request.getRequestDispatcher("/WEB-INF/mentor_view/mentorSystem.jsp").forward(request, response);
        } else if (path.contains("/mentorPreference")){
            // 具体的学生页面
            String order = request.getParameter("order");

            Mentor2 mentor2 = (Mentor2) request.getSession().getAttribute("mentor2");
            int mentorId = mentor2.getMentorId();
            SqlSession sqlSession = null;
            if (order != null) {
                int preferenceOrder = Integer.parseInt(order);
                try {
                    sqlSession = MyBatisUtil.getSqlSession("development");
                    StudentMapper2 mapper = sqlSession.getMapper(StudentMapper2.class);
                    // 获取对应学生
                    List<StudentInfo> students = mapper.getStudentsByMentor(mentorId, preferenceOrder);

                    request.setAttribute("students", students);
                    request.setAttribute("mentorId", mentorId);
                    request.setAttribute("preferenceOrder", preferenceOrder);

                    request.getRequestDispatcher("/WEB-INF/mentor_view/studentList.jsp").forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (sqlSession != null) {
                        sqlSession.close();
                    }
                }
            } else {
                // 自由选择
                try {
                    sqlSession = MyBatisUtil.getSqlSession("development");
                    FreeSelectMapper mapper = sqlSession.getMapper(FreeSelectMapper.class);

                    List<UnselectedStudent> students = mapper.getUnselectedStudents();

                    request.setAttribute("students", students);
                    request.setAttribute("mentorId", mentorId);
                    request.getRequestDispatcher("/WEB-INF/mentor_view/unselectedStudents.jsp").forward(request, response);
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (sqlSession != null) {
                        sqlSession.close();
                    }
                }
            }
        } else if (path.endsWith("/resultSystem.jsp")){
            // 进入志愿选择总页面
            Mentor2 mentor2 = (Mentor2) request.getSession().getAttribute("mentor2");
            int mentorId = mentor2.getMentorId();
            SqlSession sqlSession = null;

            try {
                sqlSession = MyBatisUtil.getSqlSession("development");
                MentorMapper mapper = sqlSession.getMapper(MentorMapper.class);
                List<Map<String, Object>> students = mapper.getMentorStudentsById(mentorId);

                request.setAttribute("mentorStudentList", students);
                request.getRequestDispatcher("/WEB-INF/mentor_view/resultSystem.jsp").forward(request, response);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        else {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "页面未找到！");
        }
    }

    @Override  // 导致选择学生
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // System.out.println(request.getRequestURI());
        String path = request.getRequestURI();
        SqlSession sqlSession = null;

        int mentorId = Integer.parseInt(request.getParameter("mentorId"));
        int studentId = Integer.parseInt(request.getParameter("studentId"));

        try{
            sqlSession = MyBatisUtil.getSqlSession("development");
            if (path.endsWith("/freeSelectStudent")) {
                FreeSelectMapper mapper = sqlSession.getMapper(FreeSelectMapper.class);
                mapper.freeSelectStudent(mentorId, studentId);
                sqlSession.commit();

                request.setAttribute("message", "成功录取ID为 " + studentId + " 的学生！");
            } else if(path.endsWith("/chooseStudent")) {
                int preferenceOrder = Integer.parseInt(request.getParameter("preferenceOrder"));
                StudentMapper2 mapper = sqlSession.getMapper(StudentMapper2.class);
                mapper.chooseStudentByMentor(mentorId, studentId, preferenceOrder);
                sqlSession.commit();

                request.setAttribute("message", "成功录取ID为 " + studentId + " 的学生！");
            } else{
                // 啥也不是
                System.out.println("error" + path);
            }
        }  catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("message", "录取失败！");
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        request.getRequestDispatcher("/result.jsp").forward(request, response);

    }
}
